<?php
namespace App\Http\Controllers\Company;

use App\Http\Controllers\Company\CompanyController;
use App\Models\CompanyInbox;
use App\Models\ResumeStatus;
use App\Models\Area;
use App\Models\CompanyFolder;
use App\Models\CompanyJobs;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use App\Models\ResumeComment;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Models\UserOther;

/**
 *
 * @author Joker
 *        
 */
class ResumeController extends CompanyController
{
    protected $status;
    
    public function __construct()
    {
        parent::__construct();
        $this->status = array('0'=>'待查看','1'=>'不符合要求','2'=>'通知面试', '3'=>'已发Offer');
        $this->gznx = array(0=>'应届毕业生',1=>'1年',2=>'2年',3=>'3年',4=>'4年',5=>'5年',6=>'6年',7=>'7年',8=>'8年',9=>'9年',10=>'10年',11=>'10年以上');
    }
 
    /**
     * 简历管理
     * @return [type] [description]
     */
    public function resume($type)
    {
        if(empty($this->userinfo->company_id))
            return redirect(url('/company/center/companyinfo-default'));
        $jobid = Input::get('job',0);
        $dg = Input::get('degree',100);
        $nx = Input::get('nx',100);
        $rst = Input::get('rst',0);
        $tm = Input::get('tm',0);
        if($type == 'offer')
        {
            $query = CompanyFolder::where('company_id','=',$this->userinfo->company_id);
        }
        else 
        {
            $query = CompanyInbox::where('company_id','=',$this->userinfo->company_id);
        }
        if($jobid)
        {
            $query->where('job_id','=',$jobid);
        }
        if($dg && $dg != 100)
        {
            $query->where('degree','=',$dg);
        }
        if($nx && $nx != 100)
        {
            $query->where('gznx','=',$nx);
        }
        if($rst)
        {
            $query->where('resume_status','=',$rst);
        }
        if($tm)
        {
            
        }
        switch ($type)
        {
            case 'unprocessed':
                $query->where('status','=',0);
                break;
            case  'notified':
                $query->where('status','=',2);
                break;
            case 'offer':
                
                break;
            case 'noway':
                $query->where('status','=',1);
                break;
            default:
                $resume = $query->paginate(10);
        }
        $resume = $query->paginate(10);
        foreach ($resume as &$res)
        {
            $res->resume = unserialize($res->resume);
            $res->edu = array_sort($res->resume->educationals->toArray(),function($value){
                return $value['graduated_at'];
            });
            if(!empty($res->resume_status))
                $res->rstatus = ResumeStatus::find($res->resume_status);
            $hasResume =  ResumeComment::where(['company_id'=>$this->userinfo->company_id,'user_id'=>$res->user_id,'resume_id'=>$res->id])->first();
            if(!empty($hasResume)){
                $res->hasComment = 1;
            }else{ 
                $res->hasComment = 0;
            }
            $res->userlevel = UserOther::where('user_id','=',$res->user_id)->first();
            $res->comments = ResumeComment::with('company')->where(['user_id'=>$res->user_id])->get();
        }
        $jobs = CompanyJobs::where(['company_id'=>$this->userinfo->company_id,'status'=>1])->get();
        $resumeStatus = ResumeStatus::all()->toArray();
        return view('company.resume')
                ->with('resumes',$resume)->with('nowjob',$jobid)->with('dg',$dg)->with('tm',$tm)->with('nx',$nx)->with('rst',$rst)
                ->with('type', $type)
                ->with('status',$this->status)
                ->with('resumeStatus',$resumeStatus)
                ->with('jobs',$jobs)
                ->with('gznx',$this->gznx)
                ->with('degree', $this->degree);
    }
    
    /**
     * 简历管理
     * @return [type] [description]
     */
    public function resumeview($id)
    {
        $resume = CompanyInbox::where(['company_id'=>$this->userinfo->company_id,'id'=>$id])->first();
        if(empty($resume))
        {
            return $this->formatJson('error','请求出错！');
        }
        $resume->resume = unserialize($resume->resume);
        $resume->logo = userlogo($resume->user_id, 'middle');
        $resume->sex = $resume->resume->sex?'女':'男';
        $resume->age = user_age($resume->resume->birth_year, $resume->resume->birth_month);
        $resume->gznxs = $this->gznx;
        $resume->gzxzs = $this->gzxz;
        $resume->degrees = $this->degree;
        $resume->salarys = $this->salary;
        if(!empty( $resume->resume->otherinfo))
        {
            $otherArea = Area::where('area_id','=', $resume->resume->otherinfo->expect_city)->first();
             $resume->resume->otherinfo->cityname = empty($otherArea)?'':$otherArea->title;
           
        }
        if($resume->resume_status > 0)
        {
           $resume->resume_status = ResumeStatus::find($resume->resume_status)->name;
        }
        else 
        {
            $resume->resume_status = '我是应届毕业生';
        }
        $resume->token = csrf_token();
        $resume->url = url('/company/center/resume/status/'.$resume->id);
        return $this->formatJson('success','成功！',$resume);
    }
    
    /**
     * 改变用户投递简历的状态
     */
    public function resumeStatus($id)
    {
        $status = Input::get('status',0);
        $inbox = CompanyInbox::where(['company_id'=>$this->userinfo->company_id,'id'=>$id])->first();
        if(empty($inbox))
            return $this->formatJson('error','数据异常');
        $inbox->status = $status;
        try {
            if($status == 3)
            {
                CompanyFolder::firstOrCreate($inbox->toArray());
            }
            $inbox->save();
            return $this->formatJson('success','成功！',$status);
        }catch (\PDOException $e){
            Log:info(['简历处理异常'=>$e->getMessage()]);
            return $this->formatJson('error','数据异常');
        }
    }
    
    /**
     * 评论
     */
    public function resumeComment(Request $req)
    {
        $data = $req->only('user_id','resume_id','level','content','exam_level');
        if(empty($this->userinfo->company_id))
            return $this->formatJson('error','企业不存在！');
        if($data['user_id'] >0 && $data['resume_id'] >0)
        {
            if( empty($data['level']) || empty($data['exam_level']))
            {
                return $this->formatJson('error','内容和评分不能为空！');
            }
            $hasResume =  ResumeComment::where(['company_id'=>$this->userinfo->company_id,'user_id'=>$data['user_id'],'resume_id'=>$data['resume_id']])->first();
            if(!empty($hasResume))
                return $this->formatJson('error','企业评论已存在！');
            $data['company_id'] = $this->userinfo->company_id;
            $data['from_company'] = 1;
            DB::beginTransaction();
            try{
                $resume = ResumeComment::firstOrCreate($data);
                $comments = DB::table('resume_comment')
                            ->select(DB::raw('sum(level) as totalLevel'),DB::raw('sum(exam_level) as totalExamLevel'),DB::raw('count(*) as total'))
                            ->where('user_id','=',$data['user_id'])
                            ->first();
                $cvgLevel = floatval($comments->totalLevel / $comments->total);
                $cvgExamLevel = floatval($comments->totalExamLevel / $comments->total);
                $userOther = UserOther::find($data['user_id']);
                $userOther->update(['interview_level'=>sprintf("%.1f", $cvgLevel),'exam_level'=>sprintf("%.1f", $cvgExamLevel)]);
                DB::commit();
            }catch (\PDOException $e){
                Log::info(['企业评论用户信用'=>$e->getMessage()]);
                DB::rollBack();
                return $this->formatJson('error','数据异常！');
            }
            return $this->formatJson('success','评论成功！',$resume);
        }
        else
        {
           return $this->formatJson('error','参数错误！'); 
        }
        
    }
}